<template>
  <div class="min-h-screen bg-white">
    <div class="flex h-full">
      <div class="ml-0 p-8 bg-gray-100" style="min-width: 1080px;padding: 2rem;">
        <div ref="contentDiv" class="p-6 mx-auto">
          <!-- 搜索区域 -->
          <div class="flex flex-wrap items-center justify-between mb-6 gap-4">
            <el-input v-model="studentAccount" placeholder="输入学号进行搜索" class="flex-grow" @keydown.enter="search">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-upload class="upload-excel" action="" :before-upload="beforeUpload" :show-file-list="false" :http-request="uploadFile" accept=".xlsx,.xls">
              <el-button type="success" class="!rounded-button whitespace-nowrap">
                <el-icon class="mr-2">
                  <Upload />
                </el-icon>
                导入 Excel 数据
              </el-button>
            </el-upload>
            <el-button type="primary" class="!rounded-button whitespace-nowrap ml-auto" @click="exportData">
              <el-icon class="mr-2">
                <Download />
              </el-icon>
              导出数据
            </el-button>
          </div>

          <!-- 地图区域 -->
          <el-card class="mb-6">
            <template #header>
              <div class="font-medium">毕业生地域分布</div>
            </template>
            <div ref="chartRef" class="w-full h-[400px]"></div>
          </el-card>

          <!-- 表格区域 -->
          <el-card>
            <template #header>
              <div class="font-medium">毕业生去向明细</div>
            </template>
            <el-table :data="students" style="width: 100%">
              <el-table-column prop="account" label="学号" />
              <el-table-column prop="userName" label="姓名" />
              <el-table-column prop="college" label="院系" />
              <el-table-column prop="major" label="专业" />
              <el-table-column prop="companyName" label="公司名" />
              <el-table-column prop="station" label="工作岗位" />
              <el-table-column prop="address" label="所在地区" />
              <el-table-column prop="wage" label="薪资范围" />
              <el-table-column prop="feedback" label="反馈" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="flex items-center justify-between mt-6">
              <div class="flex items-center gap-2">
                <div class="relative">
                  <div class="px-3 py-1 text-sm border rounded-md !rounded-button whitespace-nowrap flex items-center gap-2">
                    共 {{ totalPage }} 条信息
                    <i class="fas fa-chevron-down text-xs"></i>
                  </div>
                </div>
              </div>

              <div class="flex item-center gap-2">
                <el-pagination background v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" layout="sizes, prev, pager, next" :total="totalPage" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import 'echarts/extension/bmap/bmap';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Filter, Download, Upload } from '@element-plus/icons-vue';
import { getDestinationList, getDestinationAllList, getDestinationAddress,deleteDestination  } from '@/api/teacher/graduateDestination';
import { getToken } from '@/utils/auth';
import axios from 'axios';

// 导出文件
import { write, utils } from 'xlsx';
import { saveAs } from 'file-saver';

// 获取毕业去向数据
const AllStudent = ref([]); // 全部学生数据
const fetchDestinationAllList = async () => {
  try {
    const response = await getDestinationAllList();
    console.log("res：", response);
    AllStudent.value = response;
  } catch (error) {
    console.error('获取毕业生去向数据失败:', error);
  }
};

// 导出函数
const exportData = () => {
  fetchDestinationAllList();
  if (AllStudent.value.length === 0) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  try {
    const worksheetData = [
      ['账号', '姓名', '院系', '专业', '公司名', '工作岗位', '所在地区', '薪资范围', '反馈']
    ];

    AllStudent.value.forEach(item => {
      worksheetData.push([
        item.account,
        item.userName,
        item.college,
        item.major,
        item.companyName,
        item.station,
        item.address,
        item.wage,
        item.feedback
      ]);
    });

    const workbook = utils.book_new();
    const worksheet = utils.aoa_to_sheet(worksheetData);
    worksheet['!cols'] = [
      { wch: 15 },  // 账号
      { wch: 10 },  // 姓名
      { wch: 20 },  // 院系
      { wch: 20 },  // 专业
      { wch: 30 },  // 公司名
      { wch: 20 },  // 岗位
      { wch: 15 },  // 地区
      { wch: 15 },  // 薪资
      { wch: 40 }   // 反馈
    ];

    utils.book_append_sheet(workbook, worksheet, '毕业生去向数据');

    const wbout = write(workbook, {
      bookType: 'xlsx',
      type: 'array',
      bookSST: true
    });

    const blob = new Blob([wbout], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    saveAs(blob, `毕业生去向数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + error.message);
  }
};
// 导出文件

// 文件上传前的拦截
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件');
    return false;
  }
  return true;
};

// 文件上传请求
const uploadFile = async (options) => {
  try {
    const { file } = options;
    if (!file) {
      ElMessage.error('未选择文件');
      return;
    }

    // 创建 FormData
    const formData = new FormData();
    formData.append('file', file); // 将文件添加到 formData 中

    // 获取 token
    const token = getToken();

    // 使用 Axios 发送 POST 请求
    const response = await axios.post(
      'http://localhost:8081/destination/insertDestinationByExcel',
      formData,
      {
        headers: {
          'token': token, // 将 token 添加到请求头中
          'Content-Type': 'multipart/form-data' // 确保请求头支持 FormData
        }
      }
    );

    if (response.data.code === 200) {
      ElMessage.success('导入成功');
      // 刷新数据
      fetchDestinationList();
    } else {
      ElMessage.error(`导入失败：${response.data.message}`);
    }
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message));
  }
};

const contentDiv = ref(null);
const chartRef = ref(null);
const total = ref(156);
const studentAccount = ref('');

const students = ref([]);

const setContentWidth = () => {
  if (contentDiv.value) {
    const windowWidth = window.innerWidth;
    contentDiv.value.style.width = `${windowWidth * 0.75}px`;
    contentDiv.value.style.marginLeft = `${windowWidth * 0.175}px`;
  }
};

// 分页参数
const pageNum = ref(1);
const pageSize = ref(5);
const totalPage = ref(0); // 总数据条数

// 分页查询
const handleSizeChange = (val) => {
  pageNum.value = 1; // 切换每页条数时，重置到第一页
  pageSize.value = val;
  fetchDestinationList();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  fetchDestinationList();
};

const search = () => {
  pageNum.value = 1; // 切换每页条数时，重置到第一页
  fetchDestinationList();
};

// 获取毕业去向数据
const fetchDestinationList = async () => {
  try {
    const response = await getDestinationList({ pageNum: pageNum.value, pageSize: pageSize.value, studentAccount: studentAccount.value });
    students.value = response.rows; // 假设返回的数据中有 rows 字段
    totalPage.value = response.total; // 假设返回的数据中有 total 字段
  } catch (error) {
    console.error('获取毕业生去向数据失败:', error);
  }
};

// 新增地图数据响应式变量
const mapData = ref([]);

// 获取毕业去向统计数据
const fetchDestinationAddress = async () => {
  try {
    const response = await getDestinationAddress();
    mapData.value = response.map(item => ({
      name: item.province,  // 根据实际接口字段调整
      value: item.count   // 根据实际接口字段调整
    }));
    updateChart();
  } catch (error) {
    console.error('获取毕业生去向统计数据失败:', error);
  }
};

// 更新地图图表
const updateChart = () => {
  if (chartRef.value) {
    const myChart = echarts.init(chartRef.value);
    const option = {
      animation: false,
      title: {
        text: '2023 届毕业生地域分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      visualMap: {
        min: 0,
        max: Math.max(...mapData.value.map(item => item.value)), // 动态计算最大值
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        calculable: true,
        inRange: {
          color: ['#e0f3f8', '#2171b5']
        }
      },
      series: [
        {
          name: '毕业生人数',
          type: 'map',
          map: 'china',
          emphasis: {
            label: {
              show: true
            }
          },
          data: mapData.value
        }
      ]
    };
    myChart.setOption(option);
  }
};

onMounted(() => {
  setContentWidth();
  window.addEventListener('resize', setContentWidth);

  fetchDestinationList(); // 组件加载时调用获取毕业去向数据的方法
  fetchDestinationAddress(); // 组件加载时调用获取毕业去向地域统计数据的方法
});

// 删除功能
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '您确定要删除这条记录吗？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用删除接口
    deleteDestination(row.id).then(() => {
      ElMessage.success('删除成功');
      fetchDestinationList(); // 刷新数据
    }).catch(() => {
      ElMessage.error('删除失败');
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
</script>

<style scoped>
.el-menu {
  border-right: none;
}

.el-menu-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
}

.el-input__inner {
  border: none;
}

.el-button {
  border-radius: 0.375rem;
}

.el-card {
  border-radius: 0.5rem;
}

.el-pagination {
  justify-content: flex-end;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .flex-wrap {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>